package com.ruihang.generalibrary.utils;

import android.text.TextUtils;

import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.entity.LocalMedia;
import com.ruihang.generalibrary.beans.HtmlImageInfo;
import com.ruihang.generalibrary.beans.HtmlNodeItem;

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.Text;
import org.htmlparser.beans.StringBean;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;

import java.util.ArrayList;
import java.util.List;

public class HtmlParseUtil {
    private static final String[] TYPES = {"【视频】", "【音频】", "【图片】", "【文字】"};
    private static final String HTML_STRING = "<div class=TRS_Editor>"//
            + "<div align=\"center\"><img oldsrc=\"W020160120398575975617.jpg\" alt=\"\" style=\"border-width: 0px;\" src=\"./W020160120398575975617.jpg\" /></div>"//
            + "<b>这里是粗体哦</b>"//
            + "<div align=\"center\"><img oldsrc=\"W020160120398576595162.jpg\" alt=\"\" style=\"border-width: 0px;\" src=\"./W020160120398576595162.jpg\" /></div>"//
            + "<i>这里是斜体哦</i>"//
            + "这里什么标签都没有哦"//
            + "<embed mediatype=\"video\" src=\"aaa.mp4\"></embed>"// 视频
            + "<div align=\"center\"><img oldsrc=\"W020160120398577068194.jpg\" alt=\"\" style=\"border-width: 0px;\" src=\"./W020160120398577068194.jpg\" /></div>"//
            + "<u>这里是下划线哦</u>"//
            + "<embed mediatype=\"audio\" src=\"bbb.mp3\"></embed>"// 音频
            + "<div align=\"center\"><img oldsrc=\"W020160120398577375480.jpg\" alt=\"\" style=\"border-width: 0px;\" src=\"./W020160120398577375480.jpg\" /></div>"//
            + "<font>这里是font哦</font>"//
            + "<p aligin=\"center\">这里是p哦</p>"//
            + "<h1>这里是h1哦</h1>"//
            + "<h2>这里是h2哦</h2>"//
            + "<h3>这里是h3哦</h3>"//
            + "</div>";

    // public static void main(String[] args) {
    // List<HtmlNodeItem> nodes = parseHtml(HTML_STRING,
    // "http://oscv.net:8881/");
    // for (HtmlNodeItem node : nodes) {
    // if (node.getType() == HtmlNodeItem.TYPE_TEXT) {
    // System.out.println(TYPES[node.getType()] + " - " + node.getText());
    // } else {
    // System.out.println(TYPES[node.getType()] + " - " + node.getSrc());
    // }
    // }
    // }

    // private static String currTagName;
    private static String linkName;
    private static int lastTag = -1;
    // private static String txtSet;
    private static String txtColor;
    // private static String fontstyle;
    // private static boolean uTag = false;
    // private static boolean bold = false;
    // private static boolean em = false;
    // private static boolean strong = false;
    // private static boolean italic = false;
    // private static boolean ptag = false;

    private static String alignName;

    private static String BeginString = "";

    public static ArrayList<LocalMedia> parseImages(final String htmlStr, final String host) {
        if (TextUtils.isEmpty(htmlStr)) {
            return null;
        }
        final ArrayList<LocalMedia> imgs = new ArrayList<>();
        try {
            // htmlparser解析类
            Parser parser = new Parser();
            // 设置要解析的文本
            parser.setInputHTML(handleHtml(htmlStr));
            // 按节点过滤
            NodeVisitor visitor = new NodeVisitor() {

                @Override
                public void visitTag(Tag tag) {
                    // 获取标签名
                    String tagName = tag.getTagName().toLowerCase();
                    String src = "";
                    HtmlNodeItem node = null;
//                    curTag = tagName;
                    if (TextUtils.equals("img", tagName)) {
                        String path = tag.getAttribute("src");
                        if (!TextUtils.isEmpty(path)) {
                            path=UrlUtils.linkUrls(host,path);
                            String type = (path.endsWith(".gif") || path.endsWith(".GIF")) ? "image/gif" : "image";
                            LocalMedia lm = new LocalMedia();
                            imgs.add(new LocalMedia(path,tag.getAttribute("title"),type ));
                        }
                    }
                }

            };

            parser.visitAllNodesWith(visitor);
        } catch (Exception e)

        {
            e.printStackTrace();
        }
        return imgs;
    }

    public static List<HtmlNodeItem> parseHtml(final String htmlStr, final String host) {
        final List<HtmlNodeItem> nodes = new ArrayList<HtmlNodeItem>();
        try {
            // htmlparser解析类
            Parser parser = new Parser();
            BeginString = "";
            // 设置要解析的文本
            parser.setInputHTML(handleHtml(htmlStr));
            // 按节点过滤
            NodeVisitor visitor = new NodeVisitor() {
                private String videoImg;
                //                private String curTag;
                private boolean canCache;

                @Override
                public void visitTag(Tag tag) {
                    // 标签初始化
                    // uTag = false;
                    // bold = false;
                    // em = false;
                    // strong = false;
                    // italic = false;
                    // alignName = null;
                    // ptag = false;
                    // urrTagName = null;//
                    txtColor = null;

                    // 获取标签名
                    String tagName = tag.getTagName().toLowerCase();
                    String src = "";
                    HtmlNodeItem node = null;
//                    curTag = tagName;
                    canCache = true;
                    // 根据相应标签名调用相应处理方法
                    switch (tagName) {
                        case "img": // 图片
                            node = new HtmlNodeItem(HtmlNodeItem.TYPE_IMAGE);
                            src = tag.getAttribute("src");
                            if (!TextUtils.isEmpty(src) && src.startsWith("./")) {
                                src = host + src.substring(1);
                            }
                            node.setSrc(src);
                            nodes.add(node);
                            lastTag = HtmlNodeItem.TYPE_IMAGE;
                            break;
                        case "source":
                            String type1 = tag.getAttribute("type");

                            if (TextUtils.isEmpty(type1)) {
//							tag.getParent().getPage().get;
//							Log.e("HtmlParseUtil", "case source type empty and lastTag = "+lastTag );
                                Node n = tag.getPreviousSibling();
                                if (n != null) {
                                    String pre = n.getText();
                                    type1 = pre.split(" ")[0];
//							Log.e("HtmlParseUtil", "case source type empty and pre text = "+pre );
//							Log.e("HtmlParseUtil", "case source type empty and new type = "+type1 );
                                    if (TextUtils.isEmpty(type1)) {
                                        break;
                                    }
                                } else {
                                    break;
                                }
                            }

                            if (type1.contains("video")) {// 视频
                                node = new HtmlNodeItem(HtmlNodeItem.TYPE_VIDEO);
                                src = tag.getAttribute("src");
                                if (!TextUtils.isEmpty(src) && src.startsWith("./")) {
                                    src = host + src.substring(1);
                                }
                                node.setSrc(src);
                                if (!TextUtils.isEmpty(videoImg)) {
                                    node.setText(videoImg);
                                    videoImg = null;
                                }
                                nodes.add(node);
                                lastTag = HtmlNodeItem.TYPE_VIDEO;
                            } else if (type1.contains("audio")) // 视频
                            {
                                node = new HtmlNodeItem(HtmlNodeItem.TYPE_AUDIO);
                                src = tag.getAttribute("src");
                                if (!TextUtils.isEmpty(src) && src.startsWith("./")) {
                                    src = host + src.substring(1);
                                }
                                node.setSrc(src);
                                nodes.add(node);
                                lastTag = HtmlNodeItem.TYPE_AUDIO;
                            }
                            break;
                        case "video":
                            videoImg = tag.getAttribute("poster");
                            src = tag.getAttribute("src");
                            if (TextUtils.isEmpty(src)) {
                                break;
                            }
                            node = new HtmlNodeItem(HtmlNodeItem.TYPE_VIDEO);

                            if (!TextUtils.isEmpty(src) && src.startsWith("./")) {
                                src = host + src.substring(1);
                            }
                            node.setSrc(src);
                            nodes.add(node);
                            lastTag = HtmlNodeItem.TYPE_VIDEO;
                            break;
                        case "audio":
                            src = tag.getAttribute("src");
                            if (TextUtils.isEmpty(src)) {
                                break;
                            }
                            node = new HtmlNodeItem(HtmlNodeItem.TYPE_AUDIO);
                            if (!TextUtils.isEmpty(src) && src.startsWith("./")) {
                                src = host + src.substring(1);
                            }
                            node.setSrc(src);
                            nodes.add(node);
                            lastTag = HtmlNodeItem.TYPE_AUDIO;
                            break;
                        case "embed": {// 媒体文件
                            String type = tag.getAttribute("mediatype");
                            if ("video".equals(type)) {// 视频
                                node = new HtmlNodeItem(HtmlNodeItem.TYPE_VIDEO);
                                src = tag.getAttribute("src");
                                if (!TextUtils.isEmpty(src) && src.startsWith("./")) {
                                    src = host + src.substring(1);
                                }
                                node.setSrc(src);
                                nodes.add(node);
                                lastTag = HtmlNodeItem.TYPE_VIDEO;
                            } else if ("audio".equals(type)) {// 音频
                                node = new HtmlNodeItem(HtmlNodeItem.TYPE_AUDIO);
                                src = tag.getAttribute("src");
                                if (!TextUtils.isEmpty(src) && src.startsWith("./")) {
                                    src = host + src.substring(1);
                                }
                                node.setSrc(src);
                                nodes.add(node);
                                lastTag = HtmlNodeItem.TYPE_AUDIO;
                            }
                            break;
                        }
                        default:// 对字体的处理
                            lastTag = HtmlNodeItem.TYPE_TEXT;

                            switch (tagName) {
                                case "a":
                                    linkName = tag.getAttribute("href");
                                    if (!TextUtils.isEmpty(linkName) && linkName.startsWith("./")) {
                                        linkName = host + linkName.substring(1);
                                    }
                                    BeginString += "<a href='" + linkName + "'>";
                                    break;
                                case "font":
                                    txtColor = tag.getAttribute("color");
                                    if (!TextUtils.isEmpty(txtColor)) {
                                        BeginString += "<font color='" + txtColor + "'>";
                                    } else {
                                        BeginString += "<font>";
                                    }
                                    break;
                                case "p":
                                    alignName = tag.getAttribute("align");
                                    // if(!TextUtils.isEmpty(alignName))
                                    // {
                                    // BeginString="<p align='"+alignName+"'>";
                                    // }
                                    // else
                                    // {
                                    BeginString = "<p>";
                                    // }
                                    break;
                                case "em":
                                case "strong":
                                case "u":
                                case "b":
                                case "i":
                                case "br":
                                    BeginString += "<" + tagName + ">";
                                    break;

                                //
                                default:
                                    canCache = false;
                                    break;
                            }

                            break;
                    }
                }

                @Override
                public void visitStringNode(Text txt) {
                    String str = getText(txt.getText());

                    // String temStr = "<"+currTagName+">";
                    // if (!TextUtils.isEmpty(currTagName)) {
                    // //处理文字中的超链接
                    // if (str != null && !"a".equals(currTagName)) {//不是链接
                    // if (TextUtils.isEmpty(txtColor)) {//文章的颜色
                    // temStr = "<" + currTagName + ">" + txt.getText() + "</" +
                    // currTagName + ">";
                    // } else {
                    // temStr = "<" + currTagName + "><font color='" + txtColor
                    // + "'>" + txt.getText()
                    // + "</font></" + currTagName + ">";
                    // }
                    // } else {
                    // if (!TextUtils.isEmpty(txt.getText()) &&
                    // !TextUtils.isEmpty(linkName)) {
                    // if (TextUtils.isEmpty(txtColor)) {//链接的颜色
                    // temStr = "<a href='" + linkName + "'>" + txt.getText() +
                    // "</a>";
                    // } else {
                    // temStr = "<a href='" + linkName + "'><font color='" +
                    // txtColor + "'>"
                    // + txt.getText() + "</font></a>";
                    // }
                    // linkName = null;
                    // }
                    // }
                    // } else {
                    // if (!TextUtils.isEmpty(str)) {
                    // temStr = str;
                    // }
                    // }

                    // //字体的样式
                    //

                    if (TextUtils.isEmpty(str) || !canCache) {
                        return;
                    }
                    BeginString += str;

                    // if (lastTag == HtmlNodeItem.TYPE_TEXT &&
                    // !nodes.isEmpty()) {
                    // HtmlNodeItem nodeItem = nodes.get(nodes.size() - 1);
                    // String temp = nodeItem.getText() + temStr;
                    // nodeItem.setText(temp);
                    // } else {
                    // HtmlNodeItem node = new
                    // HtmlNodeItem(HtmlNodeItem.TYPE_TEXT);
                    // node.setText(temStr);
                    // nodes.add(node);
                    //
                    // }
                }

                @Override
                public void visitEndTag(Tag tag) {

                    String tagName = tag.getTagName().toLowerCase();

                    switch (tagName) {
                        case "a":
                        case "font":
                        case "em":
                        case "strong":
                        case "u":
                        case "b":
                        case "i":
                            BeginString += "</" + tag.getTagName().toLowerCase() + ">";
                            break;
                        case "p":
                        case "div":
                            HtmlNodeItem nodeItem = new HtmlNodeItem(HtmlNodeItem.TYPE_TEXT);
                            BeginString += "</" + tag.getTagName().toLowerCase() + ">";

                            if (!TextUtils.isEmpty(alignName)) {
                                // HtmlNodeItem nodeItem = nodes.get(nodes.size() -
                                // 1);
                                switch (alignName.toLowerCase()) {
                                    case "left":
                                        nodeItem.setType(HtmlNodeItem.TYPE_TEX_ALIGN_LEFT);
                                        break;
                                    case "center":
                                        nodeItem.setType(HtmlNodeItem.TYPE_TEX_ALIGN_CENTER);
                                        break;
                                    case "right":
                                        nodeItem.setType(HtmlNodeItem.TYPE_TEX_ALIGN_RIGHT);
                                        break;
                                    default:
                                        nodeItem.setType(HtmlNodeItem.TYPE_TEX_ALIGN_LEFT);
                                        break;
                                }

                                alignName = "";

                            }

                            nodeItem.setText(BeginString);

                            if (BeginString.equals("<p></p>")) {
                                return;
                            }

                            if (BeginString.equals("<p align='center'></p>")) {
                                return;
                            }

                            nodes.add(nodeItem);

                            BeginString = "";

                            lastTag = -1;
                            break;
                    }
                    canCache = false;

                    // uTag = false;
                    // bold = false;
                    // em = false;
                    // strong = false;
                    // italic = false;
                }
            };

            parser.visitAllNodesWith(visitor);
        } catch (Exception e)

        {
            e.printStackTrace();
        }

        return nodes;
    }

    /**
     * 根据提供的text，
     *
     * @param text 提供的纯文本信息
     * @return RL对应网页的纯文本信息
     * @throws ParserException
     */

    public static String getText(String text) {
        String returnValue = "";
        try {
            Parser parser = new Parser();
            parser.setInputHTML(text);

            StringBean sb = new StringBean();
            // 设置不需要得到页面所包含的链接信息
            sb.setLinks(false);
            // 设置将不间断空格由正规空格所替代
            sb.setReplaceNonBreakingSpaces(true);
            // 设置将一序列空格由一个单一空格所代替
            sb.setCollapse(true);
            parser.visitAllNodesWith(sb);

            returnValue = sb.getStrings();
        } catch (ParserException e) {
            e.printStackTrace();
        }
        // 返回解析后的网页纯文本信息
        return returnValue;
    }

    private static String handleHtml(String oldString) {
        if (TextUtils.isEmpty(oldString)) {
            return "";
        }

//		html = html.replaceAll( "&", "&amp;");
//		html = html.replace( "\"", "&quot;");  //"
//		html = html.replace( "\t", "&nbsp;&nbsp;");// 替换跳格
//		html = html.replace( " ", "&nbsp;");// 替换空格
//		html = html.replace("<", "&lt;");
//		html = html.replaceAll( ">", "&gt;");
        JLog.e("old String" + oldString);
        String tempStr = oldString.replaceAll("&amp;", "&").replaceAll("&quot;", "\"").replaceAll("&nbsp;&nbsp;", "\t").replaceAll("&nbsp;", " ").replaceAll("&lt;", "<").replaceAll("&gt;", ">");
        JLog.e("new String" + tempStr);
        return tempStr;
    }

}
